import re, os, shutil
from loguru import logger

pattern = re.compile(r'_?(p(\d+))-(.+?)\.[^.]+$')

work_dir = os.getenv("WORK_DIR")
output_dir = os.getenv("OUTPUT_DIR")

if not work_dir or not output_dir:
    logger.error('work_dir or output_dir is empty')
    exit(1)


def get_file_ext(fname):
    return os.path.splitext(fname)[1]


def file_tidy(file_path, index, chapter):
    file_name = os.path.basename(file_path)
    ext = get_file_ext(file_name)
    target_dir = os.path.join(output_dir, chapter)
    os.makedirs(target_dir, exist_ok=True)
    target_path = os.path.join(target_dir, f'{index}{ext}')
    if os.path.exists(target_path):
        os.remove(target_path)
    shutil.copy(file_path, target_path)
    logger.info(f'copy {file_name} to {target_path}')


def main():
    for root, dirs, files in os.walk(work_dir):
        for file in files:
            file_path = os.path.join(root, file)
            match = pattern.search(file)
            if match:
                index = match.group(2)
                chapter = match.group(3)
                logger.info(file, '→', match.group(1), 'index', index, 'chapter', chapter)
                file_tidy(file_path, index, chapter)


if __name__ == '__main__':
    main()
